package Server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;

import standard.Standard;
import recordItem.Record;
import java.io.OutputStream;

public class ThreadWriter extends Thread {
private Socket socket;
private Standard standard;

public ThreadWriter(Socket socket,Standard standard)
{
	this.socket=socket;
	this.standard=standard;
}

@Override
public void run()
{
	if(standard.getMode().equals("out"))
	{
		if(standard.getTime()==0)
		{
			standard.setTime();
		}
		boolean exist_or_not = false;
		ThreadReader.data.put(standard.getName(),standard); 
//		###For "out" should check recordArray first before store it inside the server
		System.out.println("the mode is: "+standard.getMode());
		if(ThreadReader.record_array.size()!=0)
		{
			for(Iterator it = ThreadReader.record_array.iterator();it.hasNext();)
			{
				Record record = (Record)it.next();
				Standard standard= record.getStandard();
				if(standard.getName().equals(this.standard.getName()))
				{
					exist_or_not = true;
					it.remove();
					if(standard.getMode().equals("in") || standard.getMode().equals("inAsyn"))
					{
						ThreadReturn.Search_in(standard, record.getSocket());
					}
					else
					{
						ThreadReturn.Search_read(standard, record.getSocket());
					}
				}
			}
//			if(exist_or_not == false)
//			{
//				ThreadReader.data.put(standard.getName(), standard);
//			}
		}
		if(ThreadReader.data.size()>=10)
		{
			for(String name:ThreadReader.data.keySet())
			{
				Standard standard_trial = ThreadReader.data.get(name);
				long end = System.currentTimeMillis();
				long start = standard_trial.getTime();
				long time_difference = end - start;
				System.out.println(time_difference);
				if(time_difference > 100000)
				{
					System.out.println("delete: "+time_difference);
					ThreadReader.data.remove(name,ThreadReader.data.get(name));
				}
			}
		}
	}
}
}
